package com.javaee.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import com.javaee.websocket.SpringWebSocketHandler;

@Controller
@RequestMapping("front/websocket")
public class WebsocketController {

	  @Bean//这个注解会从Spring容器拿出Bean
	    public SpringWebSocketHandler infoHandler() {
	        return new SpringWebSocketHandler();
	    }
	  
	  @RequestMapping("/login")
	  public String login(){
		  
		  return "/websocket/login";
	  }
	  
	  @RequestMapping("/websocket/login")
	    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
	        String username = request.getParameter("username");
	        System.out.println(username+"登录");
	        HttpSession session = request.getSession(false);
	        session.setAttribute("SESSION_USERNAME", username);
	        //response.sendRedirect("/quicksand/jsp/websocket.jsp");
	        return "/websocket/webSocket";
	    }

	    @RequestMapping("/websocket/send")
	    @ResponseBody
	    public String send(HttpServletRequest request) {
	        String username = request.getParameter("username");
	        String msg = request.getParameter("msg");
	        infoHandler().sendMessageToUser(username, new TextMessage(msg));
	        return "success";
	    }
}
